<template>
    <div class="px-8">
        <com-filterTable
            :ref="pageConfig.key"
            class=""
            :services="pageConfig.serviceHandle"
            :filter-form-config="pageConfig.formConfig"
            :filterInline="false"
            :params="{
                id: visitId,
            }"
            :filterCol="4"
            filterLabelWidth="90px"
            :table-border="true"
            :showFormFilter="false"
            :showRequestNum="false"
            :top-operation="pageConfig.topOperation"
            :table-column="pageConfig.columnConfig"
            :queryDataHandle="queryDataHandle"
            :dataFormatHandle="dataFormatHandle"
            :pagination="false"
            :autoLoad="true"
        />
        <com-formDialog
            ref="dialog"
            v-bind="dialogData"
            @changeOut="changeOut"
            @cancel="dialogCancelHandle"
            @submit="submitHandle"
        />
    </div>
</template>

<script>
import {
    getMedicalRecordList,
    medicalRecordAdd,
    medicalRecordUpdate,
    medicalRecordSave,
    medicalRecordDelete,
} from "@/service/api.js";
import moment from "moment";
import { formFieldDoctor } from "@/utils/formFieldDoctor";
import { MEDICAL_RECORD_OPTIONS } from "@/utils/enum.js";
import { fileUploadHandle } from "@/utils/file.js";

export default {
    name: "patientManage",
    props: {
        visitId: {
            type: [String, Number],
        },
        patientId: {
            type: [String, Number],
        },
    },
    data() {
        return {
            activeName: "filterTable",
            comDialogData: {},
            oldFormData: null,
            pageConfig: {
                key: "filterTable",
                serviceHandle: (data) => {
                    return getMedicalRecordList(data);
                },
                params: {},
                formConfig: [
                    // { key: "patientName", label: "患者姓名" },
                    // { key: "visitNo", label: "就诊号" },
                ],
                columnConfig: [
                    // { type: "select" },
                    {
                        value: "recordType",
                        label: "类型",
                        formatter: (row) => {
                            return MEDICAL_RECORD_OPTIONS.find(
                                (v) => v.key == row.recordType
                            )?.label;
                        },
                    },
                    { value: "title", label: "病历标题" },
                    { value: "content", label: "病历内容" },
                    { value: "fileUrl", label: "病历是否上传", formatter: (row) => {
                        return row.fileUrl ? "是" : "否";
                    } },
                    { value: "recordDoctorId", label: "医生" },
                    {
                        value: "recordTime",
                        label: "时间",
                        width: 160,
                        formatter: (row) => {
                            return moment(row.recordTime).format(
                                "YYYY-MM-DD HH:mm:ss"
                            );
                        },
                    },
                    {
                        value: "action",
                        type: "render",
                        label: "操作",
                        fixed: "right",
                        width: 120,
                        render: (h, { data: { row } }) => {
                            const deleteBtn = (
                                <el-button
                                    type="text"
                                    on-click={() => this.deleteList([row])}
                                >
                                    删除
                                </el-button>
                            );
                            const editBtn = (
                                <el-button
                                    type="text"
                                    on-click={() => this.addOrEditHandle(row)}
                                >
                                    修改
                                </el-button>
                            );
                            const uploadBtn = (
                                <el-button
                                    type="text"
                                    on-click={() => this.uploadFile([row])}
                                >
                                    上传病历
                                </el-button>
                            );
                            return [editBtn, deleteBtn];
                        },
                    },
                ],
                topOperation: {
                    left: [
                        {
                            name: "新增",
                            key: "add",
                            type: "primary",
                            requireArguments: ["batchSelected", "filterForm"],
                            handle: (batchSelected) => {
                                this.addOrEditHandle();
                            },
                        },
                    ],
                },
            },
        };
    },
    computed: {
        dialogData() {
            let { comDialogData } = this;
            return {
                configs:
                    this[comDialogData.configName] || comDialogData.configs,
                ...comDialogData,
            };
        },
        formDialogConfig() {
            return [];
        },
    },
    methods: {
        changeOut({ key, formData } = {}) {
            this.oldFormData = { ...formData };
        },
        dataFormatHandle(data) {
            return {
                list: data.data,
                total: data.total,
            };
        },
        queryDataHandle(params) {
            params.id = this.visitId;
            return params;
        },
        loadList() {
            let ref = this.$refs[this.activeName];
            if (Array.isArray(ref)) {
                ref = ref[0];
            }
            ref.filterFormQueryHandle();
        },
        dialogCancelHandle() {
            this.$refs.dialog.close();
        },
        async submitHandle(data) {
            let handle = this.dialogData.submitHandle;
            handle = typeof handle !== "function" ? this[handle] : handle;
            if (handle) {
                let loading = await this.$store.dispatch("global/loading");
                handle(data)
                    .then((res) => {
                        loading.close();
                        this.$refs.dialog.close();
                        this.loadList();
                    })
                    .catch((e) => {
                        console.log(e);
                        loading.close();
                    });
            }
        },
        // 上传文件
        uploadFile(row) {
            fileUploadHandle({
                fileType: 'link',
                params,
                beforeUpload: (formdata) => {
                    formdata.append("visitId", this.visitId)
                    formdata.append("id", row.id)
                    formdata.append("recordType", this.visitId)
                    formdata.append("visitId", this.visitId)
                    formdata.append("visitId", this.visitId)


                },
                onRequestSuccess: (data) => {
                    callback && callback(data);
                },
                onSuccess: (data) => {},
                onError: (data) => {},
                onProcess: (data) => {},
            });
        },
        addOrEditHandle(row) {
            let initFormData = {
                ...row,
                file: {
                    fileUrl: row.fileUrl,
                }
            }
            this.comDialogData = {
                submitHandle: (data) => {
                    let handle = medicalRecordSave;
                    let params = { ...data, visitId: this.visitId };
                    delete params.file;
                    let formdata = new FormData();

                    if (row) {
                        handle = medicalRecordSave;
                        params.id = row.id;
                    }
                    Object.keys(params).forEach((key) => {
                        formdata.append(key, params[key]);
                    });
                    if(data.file?.file) {
                        formdata.append("file", data.file.file);
                    }
                    return handle(formdata);
                },
                initFormData: initFormData,
                configs: [
                    // { key: "visitNo", label: "就诊号", required: true },
                    // { key: "patientName", label: "患者姓名", required: true },
                    {
                        key: "recordType",
                        label: "类型",
                        required: true,
                        type: "select",
                        options: MEDICAL_RECORD_OPTIONS,
                    },
                    { key: "title", label: "病历标题" },
                    { key: "file", label: "病历上传",type: 'render', render: (h,vm, configItem, data, handle ) => {
                        const uploadFile = () => {
                            fileUploadHandle({
                                fileType: 'link',
                                beforeUpload: (formdata, next, files) => {
                                    // formdata.append("visitId", this.visitId)
                                    // formdata.append("id", row.id)
                                    // formdata.append("recordType", this.visitId)
                                    // formdata.append("visitId", this.visitId)
                                    // formdata.append("visitId", this.visitId)
                                    let file = files[0]
                                    if(file) {
                                        let out = {
                                            ...(data || {}),
                                            fileUrl: file.name,
                                            file: file
                                        }
                                        handle(out)
                                    }

                                },
                                onRequestSuccess: (data) => {
                                    callback && callback(data);
                                },
                                onSuccess: (data) => {},
                                onError: (data) => {},
                                onProcess: (data) => {},
                            });
                        }
                        return (<div>
                            <div>
                                <el-button type="primary" icon="upload" on-click={uploadFile}>病历上传</el-button>
                            </div>
                            <div>
                                {data && data.fileUrl}
                            </div>
                        </div>)
                    } },
                    formFieldDoctor.user.call(
                        this,
                        "医嘱医生",
                        "recordDoctorId",
                        {
                            required: true
                        }
                    ),
                    {
                        key: "content",
                        label: "病历内容",
                        type: "editor",
                        fullLine: true,
                        default: "",
                    },
                ],
                activeRow: row,
                title: row ? "修改" : "新增",
                width: "1050px",
                height: "550px",
                labelPosition: "left",
                labelWidth: "110px",
                col: 2,
            };
            this.$refs.dialog.show();
        },
        deleteList(list) {
            this.$confirm("确认删除？").then(() => {
                this.comDialogData = {
                    submitHandle: () => {
                        return medicalRecordDelete({
                            id: list.map((v) => v.id).join(","),
                        });
                    },
                };
                this.submitHandle();
            });
        },
    },
};
</script>
